package lumis.portal.authentication;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;

import lumis.portal.dao.*;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.PortalException;
import lumis.portal.PortalObjectAlreadyExistsException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.UnexpectedException;
import lumis.util.DatabaseType;
import lumis.util.ITransaction;

/**
 * Authentication dao implementation.
 * 
 * @since 4.0.0
 * @version $Revision: 9222 $ $Date: 2008-05-08 14:40:01 -0300 (Thu, 08 May 2008) $
 */
public class AuthenticationDaoJdbc implements IAuthenticationDao
{
	public void addUserSessionId(String userSessionId, String userId) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc)PortalTransactionFactory.createTransaction();
			try
			{
				daoTransactionJdbc.begin();
				Connection connection = daoTransactionJdbc.getConnection();

				PreparedStatement statement = connection.prepareStatement("insert into lum_UserSession (userSessionId, userId, lastAccessDate) values (?, ?, ?) ");
				try
				{
					statement.setString(1, userSessionId);
					statement.setString(2, userId);

					Timestamp now = new Timestamp(System.currentTimeMillis());
					statement.setTimestamp(3, now);
					
					try
					{
						statement.executeUpdate();
					}
					catch (Exception e)
					{
						try
						{
							if (getUserId(userSessionId, daoTransactionJdbc) != null)
								throw new PortalObjectAlreadyExistsException("STR_RESOURCE_ALREADY_EXISTS;" + userSessionId, e);
							else
								throw e;
						}
						catch (PortalObjectNotFoundException e1)
						{
							throw e;
						}
					}
				}
				finally
				{
					statement.close();
				}
				
				daoTransactionJdbc.commit();
			}
			finally
			{
				daoTransactionJdbc.dispose();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public void deleteUserSessionId(String userSessionId) throws DaoException, PortalException
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			transaction.begin();
			
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("delete from lum_UserSession where userSessionId = ?");
			try
			{
				statement.setString(1, userSessionId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}
			
			transaction.commit();
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
		finally
		{
			transaction.dispose();
		}
	}

	public void deleteUserSessionByUserId(String userId) throws DaoException, PortalException
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			transaction.begin();
			
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("delete from lum_UserSession where userId = ?");
			try
			{
				statement.setString(1, userId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}
			
			transaction.commit();
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
		finally
		{
			transaction.dispose();
		}
	}

	public String validateUserSession(String userSessionId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("SELECT userId FROM lum_UserSession WHERE userSessionId=?");
			try
			{
				statement.setString(1, userSessionId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					if (resultSet.next())
						return resultSet.getString(1);
					else
						return null;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}

	public String getUserId(String userSessionId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			String userId = null;

			PreparedStatement statement = connection.prepareStatement("SELECT userId FROM lum_UserSession WHERE userSessionId=?");
			try
			{
				statement.setString(1, userSessionId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					if (resultSet.next())
						userId = resultSet.getString("userId");
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}

			return userId;
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public boolean validateUserLogin(String login, String password, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			boolean isValidUserLogin = false;

			StringBuilder Sql = new StringBuilder("SELECT userId FROM lum_User WHERE portalLogin > 0 AND UPPER(login) = UPPER(?)");

			if (password == null)
				Sql.append("and password is null");
			else
				Sql.append("and password = ?");

			PreparedStatement statement = connection.prepareStatement(Sql.toString());
			try
			{
				statement.setString(1, login);
	
				if (password != null)
					statement.setString(2, password);
	
				ResultSet resultSet = statement.executeQuery();
				try
				{
					if (resultSet.next())
						isValidUserLogin = true;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
			return isValidUserLogin;
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public void keepSessionAlive(String sessionId) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc)PortalTransactionFactory.createTransaction();
			try
			{
				daoTransactionJdbc.begin();
				Connection connection = daoTransactionJdbc.getConnection();
	
				PreparedStatement statement = connection.prepareStatement("update lum_UserSession set lastAccessDate = ? where userSessionId = ?");
				try
				{
					Timestamp now = new Timestamp(System.currentTimeMillis());
					
					statement.setTimestamp(1, now);
					statement.setString(2, sessionId);
					int count = statement.executeUpdate();
					
					if(count != 1)
						throw new PortalObjectNotFoundException("SessionId '"+sessionId+"' not found.");
				}
				finally
				{
					statement.close();
				}
				
				daoTransactionJdbc.commit();
			}
			finally
			{
				daoTransactionJdbc.dispose();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	public Collection<SessionConfig> clearInactiveSessions(int minutes, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();
			boolean dbIsMySQL = DatabaseType.MY_SQL.equals(DatabaseType.getDatabaseType());

			Collection<SessionConfig> result = new ArrayList<SessionConfig>();
			
			PreparedStatement statement = connection.prepareStatement("select userSessionId, userId from lum_UserSession where lastAccessDate < ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
			try
			{
				Calendar cal = GregorianCalendar.getInstance();
				cal.add(Calendar.MINUTE, minutes * -1);
				Timestamp now = new Timestamp(cal.getTimeInMillis());
				
				statement.setTimestamp(1, now);
				ResultSet rs = statement.executeQuery();
				try
				{
					while (rs.next())
					{
						String userSessionId = rs.getString(1);
						String userId = rs.getString(2);
						result.add(new SessionConfig(userSessionId, userId, null, false));
						rs.deleteRow();
						
						// workaround for MySQL JDBC driver
						if (dbIsMySQL)
							rs.previous();
					}
				}
				finally
				{
					rs.close();
				}
			}
			finally
			{
				statement.close();
			}
			
			return result;
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	public Collection<SessionConfig> getSessionsByUserId(String userId, ITransaction transaction) throws PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			Collection<SessionConfig> result = new ArrayList<SessionConfig>();
			
			PreparedStatement statement = connection.prepareStatement("select userSessionId from lum_UserSession where userId = ?");
			try
			{
				statement.setString(1, userId);
				ResultSet rs = statement.executeQuery();
				try
				{
					while (rs.next())
					{
						String userSessionId = rs.getString(1);
						result.add(new SessionConfig(userSessionId, userId, null, false));
					}
				}
				finally
				{
					rs.close();
				}
			}
			finally
			{
				statement.close();
			}
			
			return result;
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}
}
